package com.qiji.video.config;

import com.qiji.video.bean.Users;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class  RedisConfig {
    /*
        自定义RedisTemplate模板
        需设置序列化方式，防止java将key以16进制的方式进行操作，导致redis中取不到值
        七种序列化方式，看RedisTemplate源码
     */
    @Bean("RedisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

        RedisTemplate<String, Object> objectObjectRedisTemplate = new RedisTemplate<>();
        Jackson2JsonRedisSerializer<Users> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Users>(Users.class);

        objectObjectRedisTemplate.setConnectionFactory(redisConnectionFactory);
        // 字符串序列化
        StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();
        // 设置 redis key的序列化
        objectObjectRedisTemplate.setKeySerializer(stringRedisSerializer);
        // 设置 redis value的序列化
        objectObjectRedisTemplate.setValueSerializer(stringRedisSerializer);
        // 设置redis hash key的序列化
        objectObjectRedisTemplate.setHashKeySerializer(objectJackson2JsonRedisSerializer);
        // 设置redis hash value的序列化
        objectObjectRedisTemplate.setHashValueSerializer(objectJackson2JsonRedisSerializer);
        objectObjectRedisTemplate.afterPropertiesSet();
        return objectObjectRedisTemplate;
    }
}
